<template>
	<view class="content">
		<uv-form labelPosition="left" :model="form" ref="form">
			<view class="form_box">
				<view class="fx-row-sb-c form_item" @click="btnClick">
					<span class="ft28 flabel">所在地区</span>
					<uv-form-item prop="city" labelWidth='80'>
						<view class="fx-row-sb-c">
							<input class="form_ri1" disabled v-model="form.city" border="none" placeholder="点击选择您的地址"
								placeholder-class="places" style="background-color: #fff !important;"> </input>
							<view class="fx-row-end-c" style="width: 50rpx;text-align: center;" @click.stop="btnClick">
								<image style="width: 24rpx;height: 30rpx;" src="@/static/picture/address3.png" mode="widthFix"></image>
							</view>
						</view>
					</uv-form-item>
				</view>
				<view class="fx-row-sb-c form_item">
					<span class="ft28 flabel">门牌号</span>
					<uv-form-item prop="name">
						<input class="form_ri" v-model="form.address" maxlength="8" border="none" placeholder="请输入详细门牌号"
							placeholder-class="places"> </input>
					</uv-form-item>
				</view>
				<view class="fx-row-sb-c form_item">
					<span class="ft28 flabel">联系人</span>
					<uv-form-item prop="name" labelWidth="80">
						<input class="form_ri" v-model="form.name" maxlength="8" border="none" placeholder="请输入联系人"
							placeholder-class="places"> </input>
					</uv-form-item>
				</view>
				<view class="fx-row-sb-c form_item">
					<span class="ft28 flabel">手机号码</span>
					<uv-form-item prop="tel" labelWidth='80'>
						<input class="form_ri" v-model="form.tel" border="none" maxlength="11" type="tel" placeholder="请输入手机号"
							placeholder-class="places" @input="changetel"> </input>
					</uv-form-item>
				</view>
				<view class="fx-row-sb-c form_item" v-if="codeShow">
					<span class="ft28 flabel"></span>
					<uv-form-item prop="tel" labelWidth='80'>
						<view class="fx-row-sb-c form_ri">
							<input class="" v-model="form.code" border="none" maxlength="11" type="tel" placeholder="请输入验证码"
								placeholder-class="places" > </input>
							<uv-code class="codetxt" ref="uCode2" @change="codeChange2"   start-text="获取验证码"></uv-code>
							<text @tap="getCode2" :text="tips2" class="uv-page__code-text">{{tips2}}</text>
						</view>
					</uv-form-item>
				</view>
				<!-- <view class="fx-row-sb form_item">
					 <span class="ft28 flabel" style="margin-top: 20rpx;">详细地址</span>
					 <uv-form-item prop="address" labelWidth='80' label-align='left' class="fx-row-sb"> 
					 	<textarea style="margin-left:0px;" class="form_text"   v-model="form.address" placeholder="请输入详细门牌号" placeholder-class="places"></textarea>
					 </uv-form-item>
				 </view> -->
			</view>
			<selectAddress ref='selectAddress' @selectAddress="successSelectAddress"></selectAddress>
		</uv-form>
		<view class="select">
			<view class="select_btn" @click="submit">保存地址</view>
		</view>
	</view>
</template>

<script>
	import {
		addressEdit,
		addressAdd,
		sendSms4Address
	} from '@/utils/api.js'
	import selectAddress from '@/components/yixuan-selectAddress/yixuan-selectAddress.vue'
	import config from '@/config.js'
	import {
		toast
	} from '@/uni_modules/uv-ui-tools/libs/function/index.js'
	import request from '@/utils/request.js'
	export default {
		components: {
			selectAddress
		},
		data() {
			return {
				form: {
					'name': '',
					'tel': '',
					"city": '',
					"address": '',
				},
				state: '',
				id: '',
				latitude: '',
				longitude: '',
				addressinfo: {},
				goback: '',
				tips2: '',
				codeShow:false
			}
		},
		onLoad(option) {
			this.addressinfo = option.info ? JSON.parse(decodeURIComponent(option.info)) : ''
			console.log(this.addressinfo);
			this.state = option.state
			this.goback = option.goback
			if (option.state == 'edit') {
				this.codeShow = false
				uni.setNavigationBarTitle({
					title: '修改地址'
				});
			}
			if (option.state == 'add') {
				uni.setNavigationBarTitle({
					title: '添加地址'
				});
			}
			this.id = this.addressinfo.id
			this.form.name = this.addressinfo.name
			this.form.tel = this.addressinfo.phone
			this.form.city = this.addressinfo.region
			this.form.address = this.addressinfo.address
			this.latitude = this.addressinfo.lat
			this.longitude = this.addressinfo.lon
		},
		methods: {
			// 地图选择精确地址
			btnClick() {
				// this.$refs.selectAddress.show() 
				var _this = this
				uni.chooseLocation({
					success: (res) => {
						console.log(res);
						// this.getRegionFn(res); 
						this.latitude = res.latitude
						this.longitude = res.longitude
						this.form.city = res.address
						this.form.address = res.name 
					},
					fail: () => {
						// return;  
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												// this.handleOpenSetting()
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},
			handleOpenSetting() {
				uni.openSetting({
					success: (data) => {
						// 如果用户授权了地理信息在，则提示授权成功
						if (data.authSetting['scope.userLocation'] === true) {
							uni.showToast({
								title: "授权成功",
								icon: "success",
								duration: 1000
							})
							// 授权成功后，然后再次chooseLocation获取信息
							uni.chooseLocation({
								success: (res) => {
									console.log("详细地址", res);
									// this.getRegionFn(res);
								}
							})
						} else {
							uni.showToast({
								title: "授权失败",
								icon: "none",
								duration: 1000
							})
						}
					}
				})
			},
			// 保存地址
			submit() {
				var _this = this
				this.$refs.form.validate().then(res => {
					console.log(res, _this.$refs.form.model, "提交表单");
					if (!_this.$refs.form.model.name) {
						return uni.showToast({
							title: '请输入您的姓名',
							icon: 'none'
						})
					}
					if (!_this.$refs.form.model.tel) {
						return uni.showToast({
							title: '请输入您的手机号',
							icon: 'none'
						})
					}
					if (!/^1(2|3|4|5|6|7|8|9)\d{9}$/.test(_this.$refs.form.model.tel)) {
						return uni.showToast({
							title: '手机号格式有误',
							icon: 'none'
						})
					}
					if (!_this.$refs.form.model.city) {
						return uni.showToast({
							title: '请选择您的地址',
							icon: 'none'
						})
					}
					if (!_this.$refs.form.model.address) {
						return uni.showToast({
							title: '请输入详细门牌号',
							icon: 'none'
						})
					}
					if (this.codeShow && !_this.$refs.form.model.code) {
						return uni.showToast({
							title: '请输入验证码',
							icon: 'none'
						})
					}
					const datas = {
						'name': _this.form.name,
						'phone': _this.form.tel,
						'region': _this.form.city,
						'address': _this.form.address,
						'lon': _this.longitude,
						'lat': _this.latitude,
						'smsCode':_this.form.code
					}
					console.log(_this.state);
					if (_this.state == 'edit') {
						return this.editAddress(datas)
					}
					if (_this.state == 'add') {
						return this.addAddress(datas)
					}
				}).catch(errors => {

				})
			},
			// 添加地址
			addAddress(data) {
				uni.showLoading({
					title: '加载中'
				});
				addressAdd(data).then((res) => {
					uni.hideLoading();
					if (res.code == '200') {
						uni.showToast({
							title: '添加成功！',
							icon: 'none'
						}) 
						let pages = getCurrentPages(); // 当前页面
						let beforePage = pages[pages.length - 2]; // 上一页     
						if (this.goback == '2') {
							// #ifdef H5
							beforePage.changeAddr(res.result.id);
							// #endif
							// #ifndef H5
							beforePage.$vm.changeAddr(res.result.id);
							// #endif
						} else {
							// #ifdef H5
							beforePage.reFresh(res.result.id);
							// #endif
							// #ifndef H5
							beforePage.$vm.reFresh(res.result.id);
							// #endif
						}
						uni.navigateBack()
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 修改地址
			editAddress(data) {
				uni.showLoading({
					title: '加载中'
				});
				addressEdit({
					id: this.id,
					...data
				}).then((res) => { 
					uni.hideLoading();
					if (res.code == '200') {
						uni.showToast({
							title: '修改成功！',
							icon: 'none'
						}) 
						let pages = getCurrentPages(); // 当前页面        
						let beforePage = pages[pages.length - 2]; // 上一页        
						// #ifdef H5
						beforePage.reFresh();
						// #endif
						// #ifndef H5
						beforePage.$vm.reFresh();
						// #endif
						uni.navigateBack({
							success: function() {
								// beforePage.$vm.reFresh(); 
							}
						})

					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 输入手机号
			changetel(e){
				console.log(e); 
				if (this.state == 'edit') {
					this.codeShow = true
				}
				if(e.detail.value.length == 11){
					this.codeShow = true
				}
			},
			// 获取验证码
			getCode2() {
				var that = this;
				if (!that.form.tel) {
					return toast('请输入手机号！')
				} ///^1[3456789]\d{9}$/
				if (!(/^1(2|3|4|5|6|7|8|9)\d{9}$/.test(that.form.tel.replace(/[, ]/g, '')))) {
					return toast('请输入正确的手机号！');
				}
				if (that.$refs.uCode2.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					sendSms4Address({phone: that.form.tel,}).then((res) => {
						uni.hideLoading();
						if (res.code = '00200') {
							setTimeout(() => {
								uni.hideLoading();
								toast('验证码已发送');
								// 通知验证码组件内部开始倒计时
								that.$refs.uCode2.start();
							}, 1000);
						} else {
							toast('请稍后再试!');
						}
					}) 
				} else {
					toast('倒计时结束后再发送');
				}
			},
			codeChange2(text) {
				this.tips2 = text;
			},
			successSelectAddress(address) { //选择成功回调
				console.log(address)
				this.form.city = address
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F8F8F8;
	}

	.form_box {
		width: 670rpx;
		padding: 0 40rpx;
		margin: 15rpx 0;
		background-color: #fff;

		.form_item {
			padding: 4rpx 0;
			border-bottom: 1px solid #E6E6E6;
		}

		.form_item:last-child {
			border-bottom: 0;
		}

		.flabel {
			// padding: 10px 0;
		}

		input {
			font-size: 28rpx;
		}

		.form_label {
			width: 160rpx;
		}

		.form_ri {
			width: 500rpx;
			font-size: 28rpx;
		}

		.form_ri1 {
			width: 450rpx;
			font-size: 28rpx;
		}

		.form_text {
			width: 500rpx;
			height: 150rpx;
			padding: 0;
			font-size: 28rpx;
			border: none;
		}
	}

	.select {
		width: 750rpx;
		height: 82rpx;
		margin: 200rpx 0;
		padding: 22rpx 0;
		z-index: inherit;

		.select_btn {
			width: 690rpx;
			height: 84rpx;
			margin: 0 auto;
			border-radius: 40rpx;
			background: $uni-main;
			font-size: 32rpx;
			text-align: center;
			color: #fff;
			line-height: 84rpx;
		}
	}

	.uv-border {
		border: none;
		background-color: #fff;
	}

	.places {
		font-size: 28rpx;
		color: #999;
	}

	.uv-form-item__body__right__message {
		margin-left: 0 !important;
	}

	.codetxt,
	.uv-page__code-text {
		font-size: 28rpx;
		color: #AD8539;
	}
</style>